package pl.edu.pw.elka.tinyrepo.client;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Klasa obsługująca pobieranie pliku
 * 
 * @author Anna Stępień
 * @version 29-12-2011
 *
 */
public class DownloadHandler implements Runnable
{
	private final InputStream stream;
	private final String fileName;
	
	public DownloadHandler(final InputStream stream, final String fileName)
	{
		this.stream = stream;
		this.fileName = fileName;
	}

	@Override
	public void run()
	{
		OutputStream output = null;
		byte[] buffer = new byte[25]; // bufor do odczytywania danych
        int downloaded = 0;
        try
        {
        	File file = new File(fileName);
        	output = new FileOutputStream(file);
        	while((downloaded = stream.read(buffer)) != -1)
        	{
        		output.write(buffer, 0, downloaded);
        	}
        }
        catch (IOException e) 
        {
			e.printStackTrace();
		}
        finally
        {
        	try 
        	{
				output.close();
				stream.close();
			}
			catch (IOException e) 
			{
				e.printStackTrace();
			}
        }
	}
}
